package com.youedata.util;



import org.apache.log4j.Logger;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;


public class ReflectionUtil {

	static Logger logger = Logger.getLogger(ReflectionUtil.class);
	public static Object invokeGetterMethod(Object target, String propertyName) {
		String getterMethodName = "get" + StringUtil.changefirstCharToUpperCase(propertyName);
		return invokeMethod(target, getterMethodName, new Class[] {}, new Object[] {});
	}

	/**
	 * 调用Getter方法.
	 */
	public static Object invokeGetterMethodWithCascade(Object target, String propertyName) {
		if (propertyName != null && propertyName.indexOf(".") == -1) {
			return invokeGetterMethod(target, propertyName);
		}
		String[] properties = propertyName.split("[.]");
		Object objTaget = target;
		for (String property : properties) {
			objTaget = invokeGetterMethod(objTaget, property);
		}
		return objTaget;
	}

	/**
	 * 直接调用对象方法, 无视private/protected修饰符.
	 */
	public static Object invokeMethod(final Object object, final String methodName, final Class<?>[] parameterTypes, final Object[] parameters) {
		Method method = getDeclaredMethod(object, methodName, parameterTypes);
		if (method == null) {
			throw new IllegalArgumentException("Could not find method [" + methodName + "] on target [" + object + "]");
		}

		method.setAccessible(true);

		try {
			return method.invoke(object, parameters);
		} catch (Exception e) {
			throw convertReflectionExceptionToUnchecked(e);
		}
	}

	/**
	 * 循环向上转型,获取对象的DeclaredMethod.
	 *
	 * 如向上转型到Object仍无法找到, 返回null.
	 */
	protected static Method getDeclaredMethod(Object object, String methodName, Class<?>[] parameterTypes) {

		for (Class<?> superClass = object.getClass(); superClass != Object.class; superClass = superClass.getSuperclass()) {
			try {
				return superClass.getDeclaredMethod(methodName, parameterTypes);
			} catch (NoSuchMethodException e) {
				// Method不在当前类定义,继续向上转型
			}
		}
		return null;
	}

	/**
	 * 得到所有的属性
	 *
	 * @param entityClass
	 * @return
	 */
	public static ArrayList<Field> getAllFields(Class<?> entityClass) {
		ArrayList<Field> fs = new ArrayList<Field>();
		// 得到model所有属性
		Class<?> class1 = entityClass;
		while (!class1.getSimpleName().equals("Object")) {

			fs.addAll(Arrays.asList(class1.getDeclaredFields()));
			class1 = class1.getSuperclass();
		}
		return fs;
	}

	

	/**
	 * 得到对象属性的值（父类属性值可以取到）
	 */
	public static Object getFieldValueWithSuper(Object obj, String prepertyName) {
		try {
			Field field = getClassFieldWithSuper(obj.getClass(), prepertyName);
			if (field != null) {
				field.setAccessible(true);
				return field.get(obj);
			}
		} catch (Exception e) {
			throw ReflectionUtil.convertReflectionExceptionToUnchecked(e);
		}
		return null;
	}

	/**
	 * 得到Class的属性（包括父类属性）
	 */
	public static Field getClassFieldWithSuper(Class<?> cls, String fieldName) {
		Field[] declaredFields = cls.getDeclaredFields();
		for (Field field : declaredFields) {
			if (field.getName().equals(fieldName)) {
				return field;
			}
		}
		Class<?> superclass = cls.getSuperclass();
		if (superclass != null && !superclass.getSimpleName().equals("Object")) {
			// 递归
			return getClassFieldWithSuper(superclass, fieldName);
		}
		return null;
	}

	public static boolean isExistsClassField(Class<?> cls, String fieldName){
		return getClassFieldWithSuper(cls, fieldName)!=null;
	}




	/**
	 * 得到对象属性的值
	 *
	 * @param model
	 * @param prepertyName
	 */
	public static void setFieldValue(Object model, String prepertyName, String value) {
		Class<?>[] plusPara = { String.class };
		Object[] transPlusPara = { value };
		if(!isExistsClassField(model.getClass(),prepertyName)){
			return;
		}
		try {
			model.getClass().getMethod("set" + prepertyName.substring(0, 1).toUpperCase() + prepertyName.substring(1), plusPara).invoke(model, transPlusPara);
		} catch (Exception e) {
			throw ReflectionUtil.convertReflectionExceptionToUnchecked(e);
		}
	}

	/**
	 * 给某个对象的属性设置
	 * @author wuyw
	 * @date 2015-8-31 上午12:50:31
	 * @param model
	 * @param propertyClass
	 * @param propertyName
	 * @param propertyValue
	 */
	public static void setFieldValue(Object model, Class<?> propertyClass,  String propertyName, Object propertyValue) {
		Class<?>[] plusPara = { propertyClass };
		Object[] transPlusPara = { propertyValue };
		try {
			model.getClass().getMethod("set" + StringUtil.changefirstCharToUpperCase(propertyName), plusPara).invoke(model, transPlusPara);
		} catch (Exception e) {
			throw ReflectionUtil.convertReflectionExceptionToUnchecked(e);
		}
	}

	/**
	 * 得到对象属性的值
	 *
	 * @param model
	 * @param prepertyName
	 */
	public static void setFieldCharValue(Object model, String prepertyName, Character value) {
		Class<?>[] plusPara = { Character.class };
		Object[] transPlusPara = { value };
		try {
			model.getClass().getMethod("set" + prepertyName.substring(0, 1).toUpperCase() + prepertyName.substring(1), plusPara).invoke(model, transPlusPara);
		} catch (Exception e) {
			throw ReflectionUtil.convertReflectionExceptionToUnchecked(e);
		}
	}

	/**
	 * 得到类属性的类型
	 *
	 * @param class1
	 * @param propertyName
	 * @return
	 */
	public static Class<?> getFieldClass(Class<?> class1, String propertyName) {
		try {
			Field field = class1.getDeclaredField(propertyName);
			return field.getClass();
		} catch (Exception e) {
			throw ReflectionUtil.convertReflectionExceptionToUnchecked(e);
		}
	}

	/**
	 * 将反射时的checked exception转换为unchecked exception.
	 */
	public static RuntimeException convertReflectionExceptionToUnchecked(Exception e) {
		if (e instanceof IllegalAccessException || e instanceof IllegalArgumentException || e instanceof NoSuchMethodException) {
			return new IllegalArgumentException("Reflection Exception.", e);
		} else if (e instanceof InvocationTargetException) {
			return new RuntimeException("Reflection Exception.", ((InvocationTargetException) e).getTargetException());
		} else if (e instanceof RuntimeException) {
			return (RuntimeException) e;
		}
		return new RuntimeException("Unexpected Checked Exception.", e);
	}

	/**
	 * 设置对象属性值
	 * @param obj
	 * @param pName
	 * @param pValue
	 * @return -1属性值不存在，0失败，1成功
	 * @throws Exception
	 */
	public static int setPropertyValueByPropertyName (Object obj,String pName, String pValue,String... datePattern) throws Exception {
		// 获取javaBean属性
		BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
		PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
		int result = -1;
		if (propertyDescriptors != null && propertyDescriptors.length > 0) {
			String propertyName; // javaBean属性名
			Object propertyValue = null ; // javaBean属性值
			for (PropertyDescriptor pd : propertyDescriptors) {
				propertyName = pd.getName();
				try{
					if(!propertyName.equals(pName)){
						continue;
					}else {
						//处理int,long ,double,short,float,byte,boolean 等空值情况,这些类型值不能为null否则会报错
						if(StringUtil.isNotBlank(pValue)){
							if(pd.getPropertyType() == String.class){
								propertyValue = pValue;
							}else if((pd.getPropertyType() == int.class) || (pd.getPropertyType() == Integer.class)){
								propertyValue = Integer.valueOf(pValue);
							}else if((pd.getPropertyType() == long.class) || (pd.getPropertyType() == Long.class)){
								propertyValue = Long.valueOf(pValue);
							}else if((pd.getPropertyType() == double.class || pd.getPropertyType() == Double.class)){
								propertyValue = Double.valueOf(pValue);
							}else if((propertyValue instanceof BigDecimal) && (pd.getPropertyType() == float.class || pd.getPropertyType() == Float.class)){
								propertyValue = Float.valueOf(pValue);
							}else if(pd.getPropertyType() == short.class){
								propertyValue = Short.valueOf(pValue);
							}else if(pd.getPropertyType() == byte.class){
								propertyValue = Byte.parseByte(pValue);
							}else if(pd.getPropertyType() == Date.class){
								String patten = "yyyy-MM-ss HH:mm:ss";
								if(datePattern!=null){
									patten = datePattern[0];
								}
								propertyValue = DateUtil.getDate(pValue,patten);
							}else{
								propertyValue = pValue;
							}
							pd.getWriteMethod().invoke(obj, new Object[] { propertyValue });
						}
						result = 1;
						break;
					}
				}catch (Exception e){
					result = 0;
					StringBuilder logBuilder = new StringBuilder();
					logBuilder.append("setPropertyValueByPropertyName():").append(propertyName).append(" errmsg:").append(e.getMessage());
					logger.info(logBuilder.toString());
					e.printStackTrace();
				}
			}

		}
		return result;
	}




}
